package com.itrip.repository.Impl;

import com.itrip.document.Hotel;
import com.itrip.dto.HotelDTO;
import com.itrip.repository.HotelRepository;
import com.itrip.vo.HotelSelectVo;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Repository
public class HotelRepositoryImpl implements HotelRepository {

    @Resource
    private SolrClient solrClient;
    @Override
    public List<Hotel> selectHotelBySolr(HotelSelectVo hotelSelectVo) throws IOException, SolrServerException {
        //创建一个Solr执行对象
        SolrQuery solrQuery=new SolrQuery();
        String keyword = hotelSelectVo.getKeyword();
        if(StringUtils.isEmpty(hotelSelectVo.getKeyword())){
            solrQuery.setQuery("*:*");
        }
        solrQuery.setQuery("hotelName:"+keyword+" and address:"+keyword+"");
        solrQuery.setStart(0);
        solrQuery.setRows(6);
        //开启高亮查询
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("hotelName and address");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");

        QueryResponse query = solrClient.query("hotel",solrQuery);

        //获取查询状态
        int status = query.getStatus();
        //获取查询结果
        if(status==0){
            List<Hotel> beans = query.getBeans(Hotel.class);
            Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();

            //用高亮查询结果替换
            for(Hotel hotel:beans){
                List<String> hotelNameList = highlighting.get(hotel.getId()).get("hotelName");
                if(hotelNameList!=null&&hotelNameList.size()>0){
                    String hotelName = hotelNameList.get(0);
                    hotel.setHotelName(hotelName);
                }


                List<String> adressList = highlighting.get(hotel.getId()).get("address");
                if(adressList!=null&&adressList.size()>0){
                    String address = adressList.get(0);
                    hotel.setAddress(address);
                }
                System.out.println(hotel.toString());
            }
            return beans;
        }

       return null;
    }
}
